package com.unswift.window.editor;

import java.awt.Color;
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;

import javax.swing.JTextPane;
import javax.swing.border.AbstractBorder;
import javax.swing.text.Element;

@SuppressWarnings("serial")
public class EditorLine extends AbstractBorder {
	
	private JTextPane sqlEditor;
	private int fontWidth=-1;

	public EditorLine(JTextPane sqlEditor) {
		this.sqlEditor=sqlEditor;
	}

	/*
	 * Insets 对象是容器边界的表示形式。 它指定容器必须在其各个边缘留出的空间。
	 */
	// 此方法在实例化时自动调用
	// 此方法关系到边框是否占用组件的空间
	public Insets getBorderInsets(Component c) {
		return getBorderInsets(c, new Insets(0, 0, 0, 0));
	}

	public Insets getBorderInsets(Component c, Insets insets) {
		if (c instanceof JTextPane) {
			if(fontWidth!=-1){
				int lineCount=sqlEditor.getDocument().getDefaultRootElement().getElementCount();
				int numberLength=String.valueOf(lineCount).length();
				insets.left=fontWidth*numberLength+15;
			}else{
				insets.left = 22;
			}
		}
		return insets;

	}

	public boolean isBorderOpaque() {
		return false;
	}

	@SuppressWarnings("deprecation")
	public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
		try {
			FontMetrics fm = g.getFontMetrics();
			int fontHeight = fm.getHeight();
			fontWidth = fm.charWidth('0');
			g.setColor(new Color(170, 170, 170));
			Element root=sqlEditor.getDocument().getDefaultRootElement(), line;
			int lineCount=root.getElementCount(), start;
			int numberLength=String.valueOf(lineCount).length();
			int twidth=fontWidth*numberLength+10;
			int ybaseline=y+fontHeight-5;
			Rectangle caretRectangle;
			for (int i = 0; i < lineCount; i++) {
				line=root.getElement(i);
				start=line.getStartOffset();
				caretRectangle = sqlEditor.getUI().modelToView(sqlEditor, start);
				int currLength=String.valueOf(i+1).length();
				g.drawString((i+1)+"", (numberLength-currLength)*fontWidth+3, caretRectangle.y+fontHeight-4);
				ybaseline=caretRectangle.y+fontHeight;
			}
			g.setColor(new Color(240, 240, 240));
			g.drawLine(x+twidth+1, 0, x+twidth+1, ybaseline);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
